package com.kzd.gtboon.main.access

import android.content.Intent
import android.view.LayoutInflater
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.rxLifeScope
import com.blankj.utilcode.util.*
import com.kzd.gtboon.R
import com.kzd.gtboon.app.*
import com.kzd.gtboon.custom.setTransitionStatus
import com.kzd.gtboon.databinding.ActivityAccessBinding
import com.kzd.gtboon.entity.AccessUser
import com.kzd.gtboon.jetpack.api.appLoginOneKey
import com.kzd.gtboon.jetpack.vm.AccessViewModel
import com.kzd.gtboon.main.*
import com.kzd.gtboon.main.access.*
import com.mobile.auth.gatewayauth.*
import com.mobile.auth.gatewayauth.model.TokenRet
import com.module.lemlin.app.OwnerStatusBar
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewBindingActivity
import com.module.lemlin.owner.ownerViewModel

class AccessActivity : OwnerViewBindingActivity<ActivityAccessBinding>() {

    private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
        override fun onFragmentResumed(fm: FragmentManager, fragment: Fragment) {
            super.onFragmentResumed(fm, fragment)
            when (fragment) {
                is AccessLoginFragment -> {
                    mViewBinding.tvAccessTitle.text = "用户登录"
                }
                is AccessSettingFragment -> {
                    mViewBinding.tvAccessTitle.text = "设置"
                }
                is AccessVerifyFragment -> {
                    mViewBinding.tvAccessTitle.text = "实名认证"
                }
            }
        }
    }

    private var isStartAuthPageSuccess: Boolean = false

    private val mTokenListener: TokenResultListener = object : TokenResultListener {
        override fun onTokenSuccess(p0: String?) {
            LogUtils.e("onTokenSuccess:${p0}")
            val tokenRet = TokenRet.fromJson(p0)
            if (ResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {
                isStartAuthPageSuccess = true
            } else if (ResultCode.CODE_SUCCESS == tokenRet.code) {
                val token = tokenRet.token
                rxLifeScope.launch({
                    val resp = appLoginOneKey(token = token)
                    SPSConstance.uid = resp.data.uid
                    SPSConstance.userInfo = resp.data.userInfo
                    SPSConstance.userMine = resp.data.userMine
                    runOnUiThread {
                        mPhoneNumberAuthHelper.quitLoginPage()
                        loginSuccess(resp.data)
                    }
                }, {
                    mPhoneNumberAuthHelper.hideLoginLoading()
                    toast(it.msg)
                })
            }
        }

        override fun onTokenFailed(p0: String?) {
            LogUtils.e("onTokenFailed:${p0}")
            val tokenRet = TokenRet.fromJson(p0)
            if (isStartAuthPageSuccess && ResultCode.CODE_ERROR_USER_CANCEL != tokenRet.code) {
                toast("一键登录失败切换到其他登录方式\n${tokenRet.msg}${tokenRet.code}")
            }
            if (ResultCode.CODE_ERROR_USER_CANCEL == tokenRet.code || ResultCode.CODE_ERROR_USER_SWITCH == tokenRet.code) {
                isStartAuthPageSuccess = false
            }
            mPhoneNumberAuthHelper.hideLoginLoading()
        }
    }

    private val mPhoneNumberAuthHelper: PhoneNumberAuthHelper by lazy {
        PhoneNumberAuthHelper.getInstance(this, mTokenListener)
    }

    private val mViewModel: AccessViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater) -> ActivityAccessBinding
        get() = ActivityAccessBinding::inflate


    private val mAction: AccessAction by lazy {
        (intent?.extras?.getSerializable(KEY_ACCESS_ACTION) as? AccessAction)
            ?: AccessAction.LOGIN
    }

    private val mLoginCarrier: LoginCarrier? by lazy {
        intent?.extras?.getParcelable(KEY_ACCESS_CARRIER)
    }

    override fun initStatusBar(statusBar: OwnerStatusBar) {
        statusBar.run {
            addView = mViewBinding.flAccessBar
            barColor = R.color.white
        }
        super.initStatusBar(statusBar)
    }

    override fun initView() {

        mViewBinding.ivAccessBack.setOnClickListener { onBackPressed() }

        mViewModel.mAccessAction = mAction

        val fragment = if (mAction == AccessAction.SETTING_NICKNAME ||
            mAction == AccessAction.SETTING_QQ
        ) {
            AccessSettingFragment.newInstance()
        } else if (mAction == AccessAction.VERIFICATION) {
            AccessVerifyFragment.newInstance()
        } else {
            onKeyLogin()
            AccessLoginFragment.newInstance()
        }
        supportFragmentManager(fragment, isToBackStack = false)

        supportFragmentManager.registerFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks,
            (true)
        )

    }

    /**
     * 一键登录
     * */
    private fun onKeyLogin() {
        mPhoneNumberAuthHelper.setAuthSDKInfo(GT_AUTH_SECRET)
        mPhoneNumberAuthHelper.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN)
        val mAuthUIConfig = AuthUIConfig.Builder()
            .setLightColor(true)
            .setNavColor(ColorUtils.getColor(R.color.white))
            .setNavReturnHidden(true)
            .setNavText("用户登录")
            .setNavTextColor(ColorUtils.getColor(R.color.black))
            .setNavTextSizeDp(19)
            .setLogoImgDrawable(ResourceUtils.getDrawable(R.mipmap.logoin_logo_milu))
            .setSloganHidden(true)
            .setLogBtnBackgroundDrawable(ResourceUtils.getDrawable(R.drawable.bg_selector_50dp_ash_main))
            .setSwitchAccTextColor(ColorUtils.getColor(R.color.FF_666666))
            .setSwitchAccTextSizeDp(15)
            .setAppPrivacyColor(ColorUtils.getColor(R.color.FF_666666),
                ColorUtils.getColor(R.color.colorMain))
            .setCheckboxHidden(true)
            .create()
        mPhoneNumberAuthHelper.setAuthUIConfig(mAuthUIConfig)
        mPhoneNumberAuthHelper.getLoginToken(this, 5000)
    }

    override fun onResume() {
        super.onResume()
        if (mAction == AccessAction.LOGIN && checkLogin()) {
            mLoginCarrier?.invoke()
            finish()
        } else if (mAction == AccessAction.LOGIN_FAB && checkLogin()) {
            if (SPSConstance.userInfo?.is_new == 1) {
                mLoginCarrier?.invoke()
            }
            finish()
        } else if (mAction == AccessAction.LOGIN_CHANNEL && checkLogin()) {
            toMainActivity()
            finish()
        }
    }

    override fun initViewMode() {
        mViewModel.accessGetCodeLiveData.observe(this as LifecycleOwner, { response ->
            if (response == null) {
                return@observe
            }
            setTransitionStatus(response)
        })

        mViewModel.accessUserLiveData.observe(this as LifecycleOwner, { response ->
            setTransitionStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            loginSuccess(data)
        })

        mViewModel.userInfoLiveData.observe(this as LifecycleOwner, { response ->
            setTransitionStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            finish()
        })
    }

    override fun onBackPressed() {
        if (mAction == AccessAction.LOGIN_CHANNEL) {
            if (supportFragmentManager.backStackEntryCount > 0) {
                super.onBackPressed()
            } else {
                ActivityUtils.finishAllActivities()
            }
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        supportFragmentManager.unregisterFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks
        )
    }

    private fun loginSuccess(data: AccessUser) {

        if (mAction == AccessAction.LOGIN_AUTH) {
            setResult(AUTH_RESULT_CODE, Intent().apply {
                putExtra(AUTH_KEY_UID, data.uid)
            })
            finish()
            return
        } else if (mAction == AccessAction.LOGIN_FAB) {
            if (data.userInfo.is_new == 1) {
                mLoginCarrier?.invoke()
            }
        } else {
            mLoginCarrier?.invoke()
        }
        if (GT_FORCE_LOGIN) {
            toMainActivity()
        }
        finish()
    }


    private fun supportFragmentManager(fragment: Fragment, isToBackStack: Boolean = true) {
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (isToBackStack) {
            transaction.setCustomAnimations(
                R.animator.slide_right_in, R.animator.slide_left_out,
                R.animator.slide_left_in, R.animator.slide_right_out
            )
            transaction.replace(R.id.flAccessBody, fragment)
            transaction.addToBackStack(null)
        } else {
            transaction.replace(R.id.flAccessBody, fragment)
        }
        transaction.commit()
    }


}